using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;
public class GameController : MonoBehaviour
{
    public Transform cubeTransform;
    public float spawnRadius = 5.0f; // 生成敌人的半径
    public GameObject[] enemyPrefabs;
    public Dictionary<string, GameObject> enemies = new Dictionary<string, GameObject>(); // 使用字典存储不同名字的预制体
    public WebSocket webSocket;
    public float moveSpeed = 5.0f;

    private void Start()
    {
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && cubeTransform != null)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }
    void Update()
    {
        // Update移动逻辑
        foreach (var enemy in enemies.Values)
        {
            MoveEnemy(enemy);
        }
    }
    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));
        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            HandleUserAction(jsonData);
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }
        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }
    private void HandleUserAction(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            Debug.Log("HandleUserAction Lambda executed");

            try
            {
                Debug.Log("HandleUserAction started");

                if (jsonData["nickName"] != null)
                {
                    string username = jsonData["nickName"].ToString();

                    // 检查当前玩家是否已存在预制体对象
                    if (!enemies.ContainsKey(username))
                    {
                        // 如果不存在，创建新的预制体对象
                        GameObject newEnemy = GenerateEnemy(username, jsonData);
                        enemies.Add(username, newEnemy);
                    }
                    else
                    {
                        // 如果已存在，执行相应动作
                        // ExecuteGiftAction(enemies[username], jsonData);
                    }

                    Debug.Log("HandleUserAction: Player action processed successfully");
                }
                else
                {
                    Debug.LogError("Invalid user data in the message.");
                }

                Debug.Log("HandleUserAction completed");
            }
            catch (Exception ex)
            {
                Debug.LogError("HandleUserAction error: " + ex.Message);
            }
        });
    }
    private GameObject GenerateEnemy(string username, JObject jsonData)
    {
        if (enemyPrefabs != null && enemyPrefabs.Length > 0)
        {
            GameObject selectedPrefab = null;
            Vector3 spawnPosition = Vector3.zero; // 默认位置

            if (jsonData["giftName"] != null)
            {
                string giftName = jsonData["giftName"].ToString();

                // 根据不同礼物选择不同预制体和位置
                switch (giftName)
                {
                    case "小心心":
                        selectedPrefab = enemyPrefabs[0];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        break;

                    case "大啤酒":
                        selectedPrefab = enemyPrefabs[1];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        break;
                    case "抖音":
                        selectedPrefab = enemyPrefabs[2];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        break;
                    case "鲜花":
                        selectedPrefab = enemyPrefabs[3];
                        spawnPosition = GetRandomSpawnPosition(cubeTransform.position);
                        break;

                    default:
                        Debug.LogError("Unhandled gift type: " + giftName);
                        return null;
                }
            }

            GameObject enemy = Instantiate(selectedPrefab, spawnPosition, Quaternion.identity);
            Rigidbody enemyRigidbody = enemy.AddComponent<Rigidbody>();
            enemyRigidbody.freezeRotation = true;

            enemy.name = $"{selectedPrefab.name}_{username}";

            Debug.Log("Enemy generated at: " + spawnPosition + ", Username: " + username);

            return enemy;
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
            return null;
        }
    }
    private Vector3 GetRandomSpawnPosition(Vector3 basePosition)
    {
        Vector2 randomOffset = UnityEngine.Random.insideUnitCircle.normalized * spawnRadius;
        return basePosition + new Vector3(randomOffset.x, 0.0f, randomOffset.y);
    }

    private void MoveEnemy(GameObject enemy)
    {
        // 检查对象是否为空
        if (enemy == null)
        {
            // 处理已销毁的对象，这里你可以选择重新生成或者执行其他逻辑
            return;
        }

        // 实现移动逻辑，这里仅做示例
        enemy.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    }

    public void RemoveEnemyFromList(string username)
    {
        if (enemies.ContainsKey(username))
        {
            GameObject enemyToRemove = enemies[username];
            enemies.Remove(username);
            Destroy(enemyToRemove);
        }
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }
}
